package cn.itrip.auth.controller;

import cn.itrip.auth.exception.RedisException;
import cn.itrip.auth.exception.TokenProtectedException;
import cn.itrip.auth.service.TokenService;
import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

/**
 * @ClassName TokenController
 * @Description TODO
 * @Author yaozhaobao
 * @Date 2020/12/15 14:40
 * @Version 1.0
 **/
@RestController
@RequestMapping("/api")
public class TokenController {

    @Autowired
    TokenService tokenService;



    @RequestMapping(value = "/retoken",method = RequestMethod.POST,produces = "application/json")
    public Dto refreshToken(HttpServletRequest request){
        //获取token agent
        String  token =request.getHeader("token");
        String agent=request.getHeader("user-agent");
        ItripTokenVO itripTokenVO = null;
        //获取前端的token  agent校验用户是否有效
        if(tokenService.validateToken(token,agent)) {
            //置换token
            try {
                itripTokenVO= tokenService.refreshToken(token,agent);
            } catch (TokenProtectedException e) {
                e.printStackTrace();
               return DtoUtil.returnFail("还在保护器",ErrorCode.AUTH_PROTECTTIME_ERROR);
            } catch (ParseException e) {
                e.printStackTrace();
                return   DtoUtil.returnFail("日期转换异常",ErrorCode.AUTH_UNKNOWN);
            } catch (RedisException e) {
                e.printStackTrace();
                return  DtoUtil.returnFail(e.getMessage(),ErrorCode.AUTH_REDIS_ERROR);
            }

            return DtoUtil.returnDataSuccess(itripTokenVO);


        }else{
            return  DtoUtil.returnFail("token无效",ErrorCode.AUTH_TOKEN_INVALID);
        }

    }

}
